<?php namespace App\Utils;

use Cache;
use Log;
use App\Models\Live;
use App\Models\ViewHistory;
class CacheForWorkman {
    
    protected $LoginDataKey = 'Raylive_workman_Login_Data';//访问数
    protected $pDataKey = 'Raylive_workman_Praise_Data';//点赞数
    protected $viewHistoryKey = 'Raylive_View_History';//个人观看记录
    protected $LoginDBDataKey = 'Raylive_workman_DBLogin_Data';//直播观看人数的数据库数据
    /* *
	* @description : 清空直播访问数的缓存,写入数据库
	* @param: null
	* @return: 0 OK
        * $val = array(
           "live_id"=>$_SESSION['live_id'],
           "visit_total"=>$live['visit_total'],
           "set_visit_num"=>$live['set_visit_num'],
           "praise_total"=>$live['praise_total'],
           "set_praise_num"=>$live['set_praise_num'],
           "update_time"=>time(),
        );
	*/
	public function clearCacheVisitor(){
            $cacheKey = $this->LoginDataKey;
            $cacheObject = Cache::get($cacheKey);
//            Log::info('访问缓存:'.json_encode($cacheObject).':end');
            if(!$cacheObject || is_null($cacheObject)){
                return 0;
            }
            Cache::forget($cacheKey);
            $arr_tmp = array();
            $arr_visitor = array();
            foreach ($cacheObject['list'] as $key=>$val){
                $arr_tmp[] = $val['live_id'];
                $arr_visitor['live_id'] = $val['visit_num'];
            }
            $liveList = Live::whereIn('id', $arr_tmp)->where('is_delete', '=', 0)->get();
            foreach ($liveList as $key=>$val){
                    $val->visit_total = $val->visit_total + $arr_visitor['live_id'];
                    $val->save();
            }
            Cache::forget($this->LoginDBDataKey);//清除访问点赞的数据库缓存
//            Log::info("clearCacheVisitor OK");
            return 0;
	}
    /* *
	* @description : 清空点赞数的缓存,写入数据库
	* @param: null
	* @return: 0 OK
        * 
        room_list://每个直播的点赞数增量
            $val = array(
                "live_id"=>$_SESSION['live_id'],
                "praise_num"=>num,//这个是增量,更新数据库时要加上数据库的数字
                "update_time"=>time(),
            );
        user_list://点赞记录
            $tmp_ = array(
                "user_id"=>$_SESSION['user_id’],
                "live_id"=>$_SESSION['live_id'],
                "update_time"=>time(),
            );
	*/
	public function clearCachePraise(){
            $cacheKey = $this->pDataKey;
            $cacheObject = Cache::get($cacheKey);
//            Log::info('点赞缓存:'.json_encode($cacheObject).':end');
            if(!$cacheObject || is_null($cacheObject)){
                return 0;
            }
            Cache::forget($cacheKey);
            $arr_tmp = array();
            $arr_live = array();
            foreach ($cacheObject['room_list'] as $key=>$val){
                $arr_tmp[] = $val['live_id'];
                $arr_live['live_id'] = $val['praise_num'];
            }
            $liveList = Live::select('id','praise_total')->whereIn('id', $arr_tmp)->where('is_delete', '=', 0)->get();
            foreach ($liveList as $key=>$val){
//                Log::info("id:".$val->id.":点赞数:".$val->praise_total."增加数:".$arr_live['live_id']);
                $val->praise_total = $val->praise_total + $arr_live['live_id'];
//                Log::info(":点赞后数:".$val->praise_total);
                $val->save();
            }
//            foreach ($cacheObject['user_list'] as $key=>$val){
//                $praise = new Praise();
//                $praise->user_id = $val['user_id'];
//                $praise->live_id = $val['live_id'];
//                $praise->praise_time = $val['update_time'];//
//                $praise->is_delete = 0;
//                $praise->save();
//            }
            Cache::forget($this->LoginDBDataKey);//清除访问点赞的数据库缓存
//            Log::info("clearCachePraise OK");
            return 0;
	}
         /* *
	* @description : 清空访问记录的缓存,写入数据库
	* @param: null
	* @return: 0 OK
        * view_list:
        $val = array(
           "user_id"=>$message_data['user_id'],
            "live_id"=>$message_data['live_id'],
            "view_time"=>$message_data['view_time'],
            "update_time"=>time(),
        );
	*/
	public function clearCacheViewHistory(){
            $cacheKey = $this->viewHistoryKey;
            $cacheObject = Cache::get($cacheKey);
//            Log::info('观看记录缓存:'.json_encode($cacheObject).':end');
            if(!$cacheObject || is_null($cacheObject)){
                return 0;
            }
            Cache::forget($cacheKey);
//            $tmp = array();
//            $tmp[] = $cacheObject['view_list'][0];
//            foreach ($cacheObject['view_list'] as $k=>$v){
//                if($k >1){
//                    foreach($tmp as $m => $v_){
//                        if($v_['user_id'] == $v['user_id'] && $v_['live_id'] == $v['live_id']){
//                            if($v['update_time'] > $v_['update_time']){
//                                $tmp[$m]['update_time'] = $v['update_time'];
//                            }
//                        }
//                    }
//                }
//            }
            foreach ($cacheObject['view_list'] as $key=>$val){
                $val['live_id'] = intval($val['live_id']);
                $val['user_id'] = intval($val['user_id']);
                $liveObj = ViewHistory::select('id','view_time','update_time','device_id')
                        ->where('live_id', '=', $val['live_id'])
                        ->where('user_id', '=', $val['user_id'])
                        ->where('is_delete', '=', 0)
                        ->orderBy('update_time', 'desc')
                        ->first();
                if($liveObj){
                    $t = date('Y-m-d',$liveObj->update_time);
                    $now = date('Y-m-d');
//                    Log::info('clearCacheViewHistory if'.$t.'=='.$now);
                    if($now == $t){
                        $liveObj->view_time = $val['view_time'];
                        $liveObj->update_time = $val['update_time'];
                        $liveObj->device_id = isset($val['device_id'])?$val['device_id']:0;
                        $liveObj->save();
//                        Log::info("更新 OK"."liveId:".$liveObj->id."观看时间:".$liveObj->view_time."更新时间:".$liveObj->update_time);
                        continue;
                    }
                } 
                $live = new ViewHistory();
                $live->user_id = $val['user_id'];
                $live->live_id = $val['live_id'];
                $live->view_time = $val['view_time'];
                $live->update_time = $val['update_time'];
                $live->is_delete = 0;
                $live->device_id = isset($val['device_id'])?$val['device_id']:0;
                $live->save();
//                Log::info("插入 OK"."liveId:".$live->id."观看时间:".$live->view_time."更新时间:".$live->update_time);
                 
            }
//            Log::info("clearCacheVisitor OK");
            return 0;
	}
         /* *
	* @description : 每天把workmanlog重命名为日期文件,并清除log日志
	* @param: null
	* @return: 0 OK
	*/
	public function changeWorkmanLog(){
            $dir = './app/Service/workman/';
            $filename = 'workman.log';
            if(!file_exists($dir.$filename)){
                Log::info("workman日志不存在");
                return ;
            }
            if(filesize($dir.$filename) <= 0){
                Log::info("日志文件为空:".filesize($dir.$filename));
                return ;
            }
            $afterName = $dir."/logs/workman_".date("Y-m-d",strtotime("-1 day"));
            if(file_exists($afterName)){
                $afterName = $dir."/logs/workman_".date("Y-m-d",strtotime("-1 day"))."_1";
            }
            $cmd = "cp ".$dir.$filename." ".$afterName;
            $ret = exec($cmd);
            file_put_contents($dir.$filename, "");
            return ;
        }
}